package com.dk.uaa.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;
import org.springframework.security.oauth2.provider.code.AuthorizationCodeServices;
import org.springframework.security.oauth2.provider.code.JdbcAuthorizationCodeServices;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;

import javax.sql.DataSource;
import java.util.Arrays;

/**
 * OAuth2的配置类
 * 主要是继承AuthorizationServerConfigurerAdapter类，并实现三个方法去实现客户端配置、令牌访问端点配置，令牌安全约束
 */
@Configuration
@EnableAuthorizationServer
public class AuthorizationServer extends AuthorizationServerConfigurerAdapter {
    /**
     * 存储token配置，使用JWT存储
     */
    @Autowired
    private TokenStore tokenStore;
    /**
     * 用来实现客户端详情服务
     */
    @Autowired
    private ClientDetailsService clientDetailsService;
    /**
     * 产生token的方式，JWT
     */
    @Autowired
    private JwtAccessTokenConverter jwtAccessTokenConverter;
    /**
     * 设置授权码服务
     */
    @Autowired
    private AuthorizationCodeServices authorizationCodeServices;
    @Autowired
    private PasswordEncoder passwordEncoder;
    /**
     * 认证管理器
     */
    @Autowired
    private AuthenticationManager authenticationManager;

    /**
     * 令牌管理服务
     * 管理token
     */
    @Bean
    public AuthorizationServerTokenServices tokenServices(){
        DefaultTokenServices services = new DefaultTokenServices();
        // 客户端详情服务
        services.setClientDetailsService(clientDetailsService);
        // 支持刷新令牌
        services.setSupportRefreshToken(true);
        // 令牌存储策略
        services.setTokenStore(tokenStore);

        // 令牌增强
        TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
        tokenEnhancerChain.setTokenEnhancers(Arrays.asList(jwtAccessTokenConverter));
        services.setTokenEnhancer(tokenEnhancerChain);
        // 令牌默认有效期2消失
        services.setAccessTokenValiditySeconds(7200);
        // 刷新令牌默认有效期三天
        services.setRefreshTokenValiditySeconds(259200);
        return services;
    }


    /**
     * 设置授权码模式的授权码如何获取
     */
    @Bean
    public AuthorizationCodeServices authorizationCodeServices(DataSource dataSource){
        // 从数据库中读取
        return new JdbcAuthorizationCodeServices(dataSource);
    }

    /**
     * 自定义客户端配置
     */
    @Bean
    public ClientDetailsService clientDetailsService(DataSource dataSource){ // DataSource为我们yml文件配置的数据源，spring帮我们注入
        ClientDetailsService clientDetailsService = new JdbcClientDetailsService(dataSource);
        ((JdbcClientDetailsService)clientDetailsService).setPasswordEncoder(passwordEncoder);
        return clientDetailsService;
    }

    /**
     * 客户端的详情服务
     * clients表示客户端信息，也请求token时的clientId，secret...的信息
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        //使用从数据库中读取数据配置我们的客户端
        clients.withClientDetails(clientDetailsService);
    }

    /**
     * 令牌访问端点
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints
                .authenticationManager(authenticationManager) // 认证管理器
                .authorizationCodeServices(authorizationCodeServices) // 授权码服务
                .tokenServices(tokenServices()) //令牌管理服务
                .allowedTokenEndpointRequestMethods(HttpMethod.POST);
    }
    /**
     * 安全约束
     */
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security
                .tokenKeyAccess("permitAll()") //oauth/token_key是公开的
                .checkTokenAccess("permitAll()") //oauth/check_token公开,允许所有人访问
                .allowFormAuthenticationForClients(); //表单认证(申请令牌)
    }


}
